<template>
  <a-card :bordered="false">

    <div class="worksheetHeader flexRow table-operator">
      <div class="flex">
        <span class="title ellipsis">
<!--          this.$refs.table.refresh()-->
          <a href="javascript:" @click="refreshTable">{{ this.mdl && this.mdl.wsName || "" }}</a>
        </span>
      </div>
      <div class="valignWrapper" v-if="$appAuth(mdl)">
        <a-button v-if="selectedRowKeys.length > 0" type="danger" icon="delete" @click="handleDeleteBatch">删除</a-button>
        <a-button v-if="selectedRowKeys.length > 0" type="primary" icon="edit" @click="handleEditBatch">编辑</a-button>
        <filter-modal
          ref="filterModal"
          :fields="mdl ? mdl.fields : []"
          @filterOk="handleFilterOk"
        />
        <a-button type="primary" icon="plus" @click="handleAdd">记录</a-button>
        <a-button type="primary" icon="import" @click="handleImportExcel">Excel导入</a-button>
        <a-button type="primary" icon="export" @click="handleExportExcel">导出Excel</a-button>
      </div>
    </div>

    <a-spin :spinning="spinning">
    <s-table
      ref="table"
      size="default"
      rowKey="rowId"
      :columns="columns"
      :data="loadData"
      :alert="true"
      :rowSelection="rowSelection"
      showPagination="auto"
    >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
      <!--<span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter"/>
        </span>
      <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>-->

      <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">修改</a>
            <a-divider type="vertical"/>
            <a style="color: red" @click="handleDel(record)">删除</a>
          </template>
        </span>
    </s-table>
    </a-spin>
    <add-rows
      ref="addModal"
      :title="title"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />

    <delete-modal
      ref="deleteModal"
      :visible="delVisible"
      :loading="confirmLoading"
      :model="deleteModel"
      @cancel="handleDelCancel"
      @ok="handleDelOk"
    />

    <edit-modal
      ref="editModal"
      :visible="editVisible"
      :loading="confirmLoading"
      :fields="mdl ? mdl.fields : []"
      @cancel="handleEditCancel"
      @ok="handleEditOk"
    />

    <import-excel-data
      ref="excelModal"
      :visible="excelVisible"
      :model="mdl"
      @cancel="handleExcelCancel"
      @ok="handleExcelOk"
    />
  </a-card>
</template>

<script>
  import { Ellipsis, STable } from '@/components'
  import AddRows from '@/views/worksheet/modules/AddRows'
  import DeleteModal from '@/views/worksheet/modules/DeleteModal'
  import FilterModal from '@/views/worksheet/modules/FilterModal'
  import EditModal from '@/views/worksheet/modules/EditModal'
  import ImportExcelData from '@/views/worksheet/modules/ImportExcelData'
  import {
    deleteRow,
    addRow,
    updateWorksheetName,
    getWorksheetDetail,
    getFilterDataList,
    updateRow,
    importExcel,
    deleteRowBatch,
    updateRowBatch,
    exportExcel
  } from '@/api/worksheet'

  export default {
    name: 'WorksheetRows',
    components: {
      STable,
      Ellipsis,
      AddRows,
      DeleteModal,
      FilterModal,
      ImportExcelData,
      EditModal
    },
    data () {
      return {
        columns: [ {
          title: '#',
          scopedSlots: { customRender: 'serial' }
          }
        ],
        title: "",
        mode: 'Edit',
        visible: false,
        delVisible: false,
        editVisible: false,
        excelVisible: false,
        confirmLoading: false,
        mdl: null,
        deleteModel: null,
        isAll: false,
        // 查询参数
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const requestParameters = Object.assign({
            id: this.$route.params.id
          }, parameter, this.queryParam)
          return getFilterDataList(requestParameters)
            .then(res => {
              return res
            })
        },
        selectedRowKeys: [],
        filters: [],
        selectedRows: [],
        spinning: false
      }
    },
    methods: {
      refreshTable () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
        this.isAll = false;
      },
      handleEdit (record) {
        this.mode = 'Edit'
        this.visible = true
        this.mdl["data"] = record
      },
      doEditName (model) {
        this.confirmLoading = true
        updateWorksheetName(model).then(res => {
          this.confirmLoading = false
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.$message.info(`修改成功`)
          } else {
            this.$message.info(`修改失败`)
          }
        })
      },
      handleConfig (record) {
        this.mdl = { ...record }
        this.$router.push({
          name: 'EditWorksheet',
          params: {
            mdl: this.mdl
          }
        })
      },
      handleDel (record) {
        this.mode = "Delete"
        this.delVisible = true
        this.deleteModel = { ...record }
        this.deleteModel['name'] = record['wsName']
      },
      handleDeleteBatch () {
        this.delVisible = true
        this.mode = "DeleteBatch"
      },
      handleEditBatch () {
        this.editVisible = true
      },
      doDeleteBatch () {
        // if (this.selectedRows.length === 0) { return }
        // const ids = []
        // this.selectedRows.forEach(value => {
        //   ids.push(value.rowId)
        // })
        if (this.selectedRowKeys.length === 0) return

        // 这里取 selectedRowKeys
        const data = {
          worksheetId: this.mdl.id,
          rowIds: this.selectedRowKeys,
          isAll: this.isAll
        }
        deleteRowBatch(data).then(res => {
          this.delVisible = false
          this.confirmLoading = false
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.$refs.table.clearSelected()
            this.$message.info("删除成功")
          } else {
            this.$message.error("删除失败")
          }
        })
      },
      handleAdd () {
        this.mode = 'Add'
        this.title = '添加记录'
        this.visible = true
        this.mdl.data = {}
        // this.$router.push({ path: '/EditWorksheet' })
      },
      handleOk () {
        this.visible = false
        this.$refs.addModal.handleGetData().then(values => {
          const data = {
            worksheetId: this.mdl.id,
            data: values
          }
          if (this.mode === 'Add') {
            // 保存
            addRow(data).then(res => {
              if (res.code === 200) {
                this.$refs.table.refresh()
                this.$message.info("保存成功")
              } else {
                this.$message.error("保存失败")
              }
            })
          } else if (this.mode === 'Edit') {
            data['rowId'] = this.mdl.data && this.mdl.data.rowId
            updateRow(data).then(res => {
              if (res.code === 200) {
                this.$refs.table.refresh()
                this.$message.info("修改成功")
              } else {
                this.$message.error("修改失败")
              }
            })
          }
        })
      },
      handleCancel () {
        this.visible = false
      },
      handleDelCancel () {
        this.delVisible = false
      },
      handleExcelCancel () {
        this.excelVisible = false
      },
      handleEditCancel () {
        this.editVisible = false
      },
      handleEditOk (editData) {
        let data = {}
        if (this.isAll) {
          data = {
            worksheetId: this.mdl.id,
            isAll: true,
            filters: this.filters,
            data: editData
          }
        } else {
          data = {
            worksheetId: this.mdl.id,
            rowIds: this.selectedRowKeys,
            data: editData
          }
        }
        updateRowBatch(data).then(res => {
          this.editVisible = false
          this.confirmLoading = false
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.$message.info(`修改成功`)
          } else {
            this.$message.error(`修改失败`)
          }
        })
      },
      handleExcelOk (wsData) {
        const data = Object.assign(wsData, {
          worksheetId: this.mdl.id,
        })
        const form = this.$refs.excelModal.form
        this.excelVisible = false
        form.validateFields((errors, values) => {
          if (!errors) {
            data["values"] = values

            this.spinning = true
            importExcel(data).then(res => {
              this.spinning = false
              if (res.code === 200) {
                // this.$message.info("导入成功")
                // 弹窗提示错误信息
                if (res.data.errorData.length > 0) {
                  this.$notification["error"]({
                    message: `导入完成，共 ${res.data.fieldsData.length} 条，${res.data.errorData.length} 条数据有误`,
                    duration: null,
                    placement: 'bottomRight',
                    style: {
                      width: '420px'
                    },
                    description: () => {
                      const errorData = res.data.errorData
                      let msg = ''
                      for (let i = 0; i < errorData.length; i++) {
                        msg += errorData[i].errMsg + "\r\n"
                      }
                      return msg
                    }
                  });
                } else {
                    this.$notification["success"]({
                      message: `导入完成，共 ${res.data.fieldsData.length} 条，${res.data.fieldsData.length} 条成功`,
                      duration: 5,
                      placement: 'bottomRight'
                    })
                }
                // 刷新表格
                this.$refs.table.refresh()
              } else {
                this.$notification["error"]({
                  message: `导入失败`,
                  placement: 'bottomRight',
                  description: res.msg
                });
              }
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleDelOk (record) {
        this.confirmLoading = true
        if (this.mode === "Delete") {
          deleteRow({ rowId: record.rowId, worksheetId: this.mdl.id }).then(res => {
            this.delVisible = false
            this.confirmLoading = false
            if (res.code === 200) {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.info(`删除成功`)
            } else {
              this.$message.error(`删除失败`)
            }
          })
        } else if (this.mode === "DeleteBatch") {
          this.doDeleteBatch()
        }
      },
      handleFilterOk (filters) {
        const id = this.$route.params.id;
        this.filters = filters;

        this.queryParam = {
          "id": id,
          "wsCollection": "ws" + id,
          "filters": filters
        }

        this.$refs.table.refresh();
      },
      getColumns () {
        const id = this.$route.params.id
        getWorksheetDetail(id).then(res => {
          if (res.code === 200) {
            this.mdl = Object.assign(res.data, {
              data: {}
            })
            if (this.mdl && this.mdl.fields) {
              // console.log(this.mdl)
              const jsonData = JSON.parse(this.mdl.config)
              this.mdl.fields.forEach(field => {
                jsonData.list.forEach(f => {
                  if (field.name === f.key) {
                    f.options = field.options
                  }
                })
              })
              this.mdl.config = JSON.stringify(jsonData)

              this.mdl.fields = this.mdl.fields.filter(field => field.options.hidden !== true)
              this.mdl.fields.forEach(field => {
                // 图片
                if (field.dataType === 46) {
                  return
                }

                let column = {}
                if (field.dataType === 5 && field.options && field.options.unit) {
                  column = {
                    title: field.alia + ` (${field.options.unit})`,
                    dataIndex: field.name
                  }
                } else {
                  column = {
                    title: field.alia,
                    dataIndex: field.name
                  }
                }
                this.columns.push(column)
              })
              if (this.$appAuth(this.mdl)) {
                this.columns.push({
                  title: '操作',
                  dataIndex: 'action',
                  width: '200px',
                  scopedSlots: { customRender: 'action' }
                })
              }
            }
          }
        })
      },
      handleImportExcel () {
        // 上传excel文件
        this.excelVisible = true
      },
      handleExportExcel () {
        // 导出 excel
        const data = { worksheetId: this.mdl.id, filters: this.filters }
        exportExcel(data).then(res => {
          const name = decodeURI(res.headers['content-disposition'].split(';')[1].split('filename=')[1])
          this.postDownload(res.data, name)
        })
      },
      postDownload (blob, filename) {
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // IE
          window.navigator.msSaveBlob(blob, filename);
        } else {
          const URL = window.URL || window.webkitURL;
          const downloadUrl = URL.createObjectURL(blob);
          if (filename) {
            // use HTML5 a[download] attribute to specify filename
            const a = document.createElement('a');
            // safari doesn't support this yet
            if (typeof a.download === 'undefined') {
              window.location = downloadUrl;
            } else {
              a.href = downloadUrl;
              a.target = '_blank';
              a.download = filename;
              document.body.appendChild(a);
              a.click();
            }
          } else {
            window.location = downloadUrl;
          }
          setTimeout(() => { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
    }
  }
    },
    computed: {
      rowSelection () {
        const self = this;
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
          hideDefaultSelections: true,
          selections: [
            {
              key: 'current-page-data',
              text: '选择本页记录',
              onSelect: changeableRowKeys => {
                self.selectedRowKeys = changeableRowKeys;
                self.selectedRows = [];
                self.isAll = false;
              }
            },
            {
              key: 'all-data',
              text: '选择全部记录',
              onSelect: changeableRowKeys => {
                self.selectedRowKeys = changeableRowKeys;
                self.selectedRows = [];
                self.isAll = true;
              }
            }
          ]
        }
      }
    },
    mounted () {
      this.getColumns()
    }
  }
</script>

<style lang="less" scoped>
  @import "worksheet";

  .worksheetHeader {
    padding-left: 10px;
    padding-right: 20px;
    height: 38px;
    background: #fff;
    align-items: center;
  }
  .title {
    vertical-align: middle;
    display: inline-block;
    max-width: 17em;
    font-size: 17px;
    color: #333;
    font-weight: 700;
  }
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .valignWrapper {
    display: -webkit-flex;
    display: flex;
    -webkit-align-items: center;
    align-items: center;
  }
</style>
